package com.example.demo.controller;

import com.example.demo.utils.DateUtil;
import com.example.demo.utils.OperationResult;
import com.example.demo.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.Objects;

/**
 * Created by liulanhua on 2018/4/26.
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    private String path = "d:\\file\\";

    @GetMapping(value = "")
    public ModelAndView index(ModelAndView mv) {
        mv.addObject("record", "this is file page");
        mv.setViewName("file");
        return mv;
    }

    @PostMapping(value = "/upload", produces = "application/json;charset=UTF-8")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());
        File localFile = new File(path, Objects.requireNonNull(file.getOriginalFilename()));
        file.transferTo(localFile);
        return new ResponseEntity<>(path, HttpStatus.OK);
    }

    @PostMapping(value = "/upload2", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = "application/json;charset=UTF-8")
    public ResponseEntity<Result<String>> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        log.info("文件上传" + file.getName());
        String filePath = "";
        try {
            //String uploadUrl = request.getSession().getServletContext().getRealPath(File.separatorChar + "uploadFile" + File.separatorChar);
            String uploadUrl = "/usr/local/app2/uploadFile";
            //uploadUrl = "E:\\giteespace\\springboot-thymeleaf-demo\\uploadFile";
            String dateUri = DateUtil.date2Str(new Date(), DateUtil.DATE_FORMAT_MONTH_PATTERN1);
            uploadUrl = uploadUrl + File.separatorChar + dateUri;
            File folder = new File(uploadUrl);
            if (!folder.isDirectory()) {
                boolean mkdir = folder.mkdirs();
                if (!mkdir) {
                    return new ResponseEntity<>(new Result<String>().invokeFail(OperationResult.BLLFileUploadError.getCode(), "文件上传创建文件目录失败! "), HttpStatus.OK);
                }
            }
            String oldName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(oldName)) {
                String suffixName = oldName.substring(oldName.lastIndexOf("."), oldName.length());
                String newName = oldName.substring(0, oldName.lastIndexOf(".")) + System.currentTimeMillis() + suffixName;
                File uploadFile = new File(uploadUrl, Objects.requireNonNull(file.getOriginalFilename()));
                FileWriter out = new FileWriter(uploadFile);
                out.close();
                File newNameFile = new File(uploadUrl, newName);
                boolean renameTo = uploadFile.renameTo(newNameFile);
                if (!renameTo) {
                    return new ResponseEntity<>(new Result<String>().invokeFail(OperationResult.BLLFileUploadError.getCode(), "文件重命名失败! "), HttpStatus.OK);
                }
                file.transferTo(newNameFile);

                String contextPath = "/";
                if (StringUtils.isNotBlank(contextPath)) {
                    if (contextPath.length() == 1) {
                        contextPath = "";
                    } else {
                        if (contextPath.startsWith("/")) {
                            contextPath = contextPath.substring(1, contextPath.length());
                        }
                        if (contextPath.endsWith("/")) {
                            contextPath = contextPath.substring(0, contextPath.length() - 1);
                        }
                    }
                }
                if (StringUtils.isBlank(contextPath)) {
                    filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                            + File.separatorChar + "uploadFile" + File.separatorChar + dateUri + File.separatorChar + newName;
                } else {
                    filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                            + File.separatorChar + contextPath + File.separatorChar + "uploadFile" + File.separatorChar + dateUri + File.separatorChar + newName;
                }

                log.info("文件上传路径filePath ={}", filePath);
            }
        } catch (IOException e) {
            log.error("文件上传异常! ", e);
            return new ResponseEntity<>(new Result<String>().invokeFail(filePath, OperationResult.BLLFileUploadError.getCode(), "文件上传异常! "), HttpStatus.OK);
        }
        return new ResponseEntity<>(new Result<String>().invokeSuccess(filePath, null), HttpStatus.OK);
    }

    @GetMapping("/download/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
        try (InputStream inputStream = new FileInputStream(new File(path, id + ".jpg"));
             OutputStream outputStream = response.getOutputStream();) {

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + id + ".jpg");

            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
